package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

//手写负载均衡算法
@Component
public class MyLB implements LoadBalance {
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    public final int getAndIncrement(){
        int current;
        int next;
        do{
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current+1;//当next下标大于MAX_VALUE时，清零，重写累加
        }while (!this.atomicInteger.compareAndSet(current,next));//如果当前值和预期值一致，则this.atomicInteger.compareAndSet(current,next)为true
                                                                    // !true则为false，跳出do while循环，打印出信息
        System.out.println("**********第几次访问，次数next："+next);
        return next;
    }

    //ribbon负载均衡算法原理：rest接口第几次请求数 % 服务器集群总数 = 实际调用服务器位置下标
    //每次重启后，rest接口计数从1开始
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }
}
